package de.slothsoft.bookmaker.pdf;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Image;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.PdfWriter;

import de.slothsoft.bookmaker.ProgressMonitor;

public class ITextPdfCreator implements PdfCreator {

    private final File folder;

    public ITextPdfCreator(File folder) {
        this.folder = folder;
    }

    @Override
    public void createPdf(ProgressMonitor monitor, PdfRequest request) throws IOException {
        Document document = new Document();
        try (OutputStream out = new FileOutputStream(new File(this.folder, cleanUp(request.getDisplayName()) + ".pdf"))) {
            PdfWriter.getInstance(document, out);
            document.open();

            Rectangle rectangle = document.getPageSize();
            for (String imageUrl : request.getImageUrls()) {
                monitor.setText("Added image URL: " + imageUrl);
                Image image = Image.getInstance(new URL(imageUrl));
                image.setAbsolutePosition(0, 0);
                image.scaleAbsolute(rectangle.getWidth(), rectangle.getHeight());
                document.add(image);
                document.newPage();
                monitor.incrementValue();
            }
            document.close();
        } catch (DocumentException e) {
            throw new IOException(e);
        }
    }

    private static String cleanUp(String displayName) {
        return displayName.replace(":", "");
    }
}
